#include "Init.h"

#define SCREEN_HEIGHT 640
#define SCREEN_WIDTH 495
#define SCREEN_BPP 32
#define SCREEN_NAME "Black Jack"

/*
Priority in MySDL_Load_Image:
0 - picture
1 - card image
2 - background
*/

Init::Init()
{
	screen = image = background_image = NULL;
	buffer_count = 0;
	
	for (int i = 0; i < 100; i++)
		image_buf[i] = NULL;
	
	if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
		perror("SDL_Init");
		exit(0);
	}
	
	screen = SDL_SetVideoMode(SCREEN_HEIGHT, SCREEN_WIDTH,
				  SCREEN_BPP, SDL_SWSURFACE);
	
	if (!screen) {
		perror("SDL_SetVideoMode");
		exit(0);
	}
	
	SDL_WM_SetCaption(SCREEN_NAME, 0);
}

bool Init::MySDL_Load_Image(std::string filename, unsigned int priority, unsigned int picture_nb)
{
	SDL_Surface *picture = NULL;
	
	if (!(picture = IMG_Load(filename.c_str())))
		return false;
	else
		picture = SDL_DisplayFormat(picture);
	
	if (priority == 0) {
		image_buf[buffer_count++] = picture;
		picture_nb = buffer_count - 1;	//Information where the picture is stored
	}
	else if (priority == 1)
		image = picture;
	else if (priority == 2)
		background_image = picture;
	else
		return false;
	return true;
}

bool Init::MySDL_ApplySurface(int x, int y, SDL_Surface *src, SDL_Surface *dest, SDL_Rect *clip)
{
	SDL_Rect offset;
	
	offset.x = x;
	offset.y = y;
	
	if (SDL_BlitSurface(src, clip, dest, &offset) == -1)
		return false;
	else {
		SDL_Flip(dest);
		return true;
	}
}

SDL_Surface *Init::GetScreenAddress()
{
	return screen;
}

SDL_Surface *Init::GetImageAddress()
{
	return image;
}

SDL_Surface *Init::GetBackgroundImageAddress()
{
	return background_image;
}

SDL_Surface *Init::GetBufferImageAddress(int picture_nb)
{
	return image_buf[picture_nb];
}

std::string Init::ConvertIntToString(int nb)
{
	std::stringstream number;
	number << nb;
	return number.str();
}

/*
	Delete piece of screen where score and
	cash are present. For computer x is always 0
	and y will be CARD_SCORE_POS_COMP_Y and
	SCORE_POS_COMP_Y. For human will be
	CARD_SCORE_POS_HUMAN_Y and SCORE_POS_HUMAN_Y
*/
bool Init::DeletePieceOfScreen(int x, int y, int h, int w)
{
	SDL_Rect offset;
	SDL_Rect Clip;
	offset.x = x;
	offset.y = y;
	
	Clip.x = 0;
	Clip.y = 0;
	Clip.h = h;
	Clip.w = w;
	
	if (SDL_BlitSurface(background_image, &Clip, screen, &offset) == -1)
		return false;
	else {
		SDL_Flip(screen);
		return true;
	}
}